import {
	Toast
} from 'vant'
import {
	getuserInfoAPI
} from '@/api/user.js'

import {
	CHANGE_LOGIN_STATE,
	SET_TOKEN,
	SET_USERINFO,
	SET_UID,
	LOGOUT
} from './mutation-types.js'

export default {
	namespaced:true,
	state: {
		isLogin: false,
		token: null,
		userInfo: {},
		uid: null
	},
	getters: {},
	// 更改数据的方法
	mutations: {
		[CHANGE_LOGIN_STATE](state, val) {
			state.isLogin = val
		},
		[SET_TOKEN](state, val) {
			state.token = val
		},
		[SET_USERINFO](state, val) {
			state.userInfo = val
		},
		[SET_UID](state, val) {
			state.uid = val
		},
		[LOGOUT](state) {
			state.isLogin = false
			state.token = null
			state.userInfo = {}
			state.uid = null
		}
	},
	actions: {
		getuserInfo({
			state,
			commit
		}, token) {
			let t1 = Toast.loading({
				message: '加载中...',
				forbidClick: true,
			});
			return getuserInfoAPI({
				token
			}).then(res => {
				let {
					uid,
					userInfo
				} = res;
				//  所有的 更改state状态的操作 都需要使用commit  去触发mutations里的方法
				commit('CHANGE_LOGIN_STATE', true)
				commit('SET_TOKEN', token)
				commit('SET_USERINFO', userInfo)
				commit('SET_UID', uid)

				setTimeout(v => {
					t1.clear()
				}, 300)
			})
		}
	},
	modules: {}
}
